package com.syl.springcloud.remote.config.listener;

import com.syl.springcloud.remote.config.util.CommonUtils;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.MutablePropertySources;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 *  注入远程配置服务列表配置
 * @author syl
 * @create 2018-08-02 10:28
 **/
public class remoteConfigListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {

    @Override
    public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
        ConfigurableEnvironment environment = event.getEnvironment();
        MutablePropertySources propertySources = environment.getPropertySources();
        Map<String, Object> myMap = new HashMap();
        Properties properties = CommonUtils.getFileProperties("remote-config.properties");
        myMap.put("spring.cloud.config.fail-fast", Boolean.valueOf(properties.getProperty("remote.config.fail-fast","true")));
        myMap.put("spring.cloud.config.label", properties.getProperty("remote.config.label","master"));
        List<String> remoteConfigUri = CommonUtils.getPropertiesList(properties, "remote.config.uri");
        for (int i = 0; i < remoteConfigUri.size(); i++) {
            myMap.put("spring.cloud.config.uri["+i+"]", remoteConfigUri.get(i));
        }
        propertySources.addFirst(new MapPropertySource("myRemoteConfig", myMap));
    }

}
